package com.dl.redis.controller;

import com.dl.redis.util.LockContext;
import com.dl.redis.util.RedisLockUtil;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author DL
 * @create 2023-09-11 15:43
 */
@RestController
@RequestMapping("/redis")
public class RedisController {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private RedisLockUtil redisLockUtil;

    @RequestMapping("/set/{value}")
    public String test(@PathVariable String value){
        redisTemplate.opsForValue().set("name", value);
        return "hello redis";
    }

    @RequestMapping("/lock")
    public String lock(){
        boolean flag = redisLockUtil.lock();
        return "加锁结果:" + flag;
    }

    @RequestMapping("/unlock")
    public String unlock(){
        try {
            redisLockUtil.unlock();
            return "解锁成功";
        }catch (Exception e){
            return e.getMessage();
        }
    }

    @RequestMapping("/getUuid")
    public String getUuid(){
        return LockContext.getLockUuid();
    }

    @RequestMapping("/setUuid")
    public void setUuid(){
        LockContext.setLockUuid("abc");
    }

    @RequestMapping("/setAndGet")
    public String setAndGet(){
        LockContext.setLockUuid("abc");
        return LockContext.getLockUuid();
    }


    @RequestMapping("/doSomething")
    public String doSomething() {
        boolean locked = redisLockUtil.lock();
        String msg;
        try {
            if (locked) {
                msg = "正在执行任务...";
                TimeUnit.SECONDS.sleep(5);
            } else {
                msg = "无法获取锁...";
            }
        } catch (InterruptedException e) {
            msg = "执行任务出错...";
        } finally {
            // 无论如何都要释放锁
            redisLockUtil.unlock();
        }
        return msg;
    }
}
